<template>
    <el-row :gutter="20">
        <el-col :sm="24">
            <el-row :gutter="20" style="margin: 0;">
                <!-- 左侧：软件分类和搜索 -->
                <div class="left-panel">
                    <el-card class="category-card">
                        <div class="card-header">
                            <h3>软件分类</h3>
                        </div>
                        <div class="category-list"
                            :style="{ height: windowStore.winHeight - 190 - (windowStore.isMaximized ? 20 : 0) + 'px' }">
                            <el-menu :default-active="activeTab" @select="handleCategorySelect">
                                <el-menu-item v-for="category in categories" :key="category.id"
                                    :index="category.id.toString()">
                                    <span>
                                        <el-icon v-if="category.icon">
                                            <component :is="category.icon" />
                                        </el-icon>
                                        <span class="category-name">{{ category.name }}</span>
                                    </span>
                                    <el-badge :value="getCategoryCount(category.id)"
                                        :type="category.id.toString() === activeTab ? 'primary' : 'info'"
                                        class="category-badge" />
                                </el-menu-item>
                            </el-menu>
                        </div>
                    </el-card>
                </div>

                <!-- 右侧：软件列表 -->
                <div class="right-panel">
                    <el-card>
                        <div class="card-header">
                            <div class="search-wrapper">
                                <el-input v-model="searchKeyword" placeholder="请输入软件名称" clearable @clear="handleSearch"
                                    @keyup.enter="handleSearch">
                                    <template #append>
                                        <el-button :icon="Search" @click="handleSearch" />
                                    </template>
                                </el-input>
                            </div>
                            <div class="header-actions">
                                <el-button :icon="Download" circle @click="handleDownloadPage" />
                                <el-divider direction="vertical" border-style="dashed" />
                                <el-text type="info" size="small">
                                    共 {{ filteredSoftList.length }} 个软件
                                </el-text>
                            </div>
                        </div>

                        <!-- 软件卡片列表 -->
                        <div class="software-list-container"
                            :style="{ height: windowStore.winHeight - 230 - (windowStore.isMaximized ? 20 : 0) + 'px' }">
                            <el-row :gutter="20">
                                <el-col v-for="software in paginatedSoftList" :key="software.id" :xs="24" :sm="12"
                                    :md="8" :lg="6" style="margin-bottom: 20px">
                                    <el-card :body-style="{ padding: '15px' }" class="software-card">
                                        <div class="software-icon">
                                            <el-image :src="software.icon || defaultIcon" class="image" fit="cover"
                                                :alt="software.name" lazy />
                                        </div>
                                        <div class="software-info">
                                            <h4 class="software-name" :title="software.name">{{ software.name }}</h4>
                                            <p class="software-version">版本: {{ software.version }}</p>
                                            <p class="software-size">大小: {{ software.size }}</p>
                                            <div class="software-status">
                                                <el-tag :type="getDownloadStatusType(software.downState)" size="small">
                                                    {{ getDownloadStatusText(software.downState) }}
                                                </el-tag>
                                                <el-tag :type="getInstallStatusType(software.installState)" size="small"
                                                    style="margin-left: 5px">
                                                    {{ getInstallStatusText(software.installState) }}
                                                </el-tag>
                                            </div>
                                            <div class="software-actions">
                                                <el-button type="primary" size="small"
                                                    :loading="downloading[software.id]"
                                                    @click="handleDownload(software)"
                                                    :disabled="software.downState === 1 || software.downState === 2">
                                                    {{ software.downState === 2 ? '已下载' : '下载' }}
                                                </el-button>
                                                <el-button type="success" size="small"
                                                    :disabled="software.installState === 1 || software.installState === 2 || software.downState !== 2"
                                                    @click="handleInstall(software)" style="margin-left: 10px">
                                                    {{ software.installState === 1 ? '已安装' : software.installState === 2
                                                    ? '安装中' : '安装' }}
                                                </el-button>
                                            </div>
                                        </div>
                                    </el-card>
                                </el-col>
                            </el-row>
                        </div>
                        <!-- 分页 -->
                        <div class="pagination-container">
                            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                                :total="filteredSoftList.length" :page-sizes="[8, 16, 24, 32]"
                                layout="total, sizes, prev, pager, next, jumper" background
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                        </div>
                    </el-card>
                </div>
            </el-row>
        </el-col>
    </el-row>
</template>

<script>
    import { h, ref, computed, reactive, onMounted, onUnmounted } from 'vue'
    import { Refresh, Search, Download } from '@element-plus/icons-vue'
    import * as ElementPlusIconsVue from '@element-plus/icons-vue'
    import { useWindowStore } from '/src/stores/windowStore'
    import { ElMessage, ElLoading } from 'element-plus'
    import { ipcRenderer } from 'electron'
    import path from 'path'

    export default {
        name: 'SoftList',
        components: { ...ElementPlusIconsVue },
        setup() {
            const windowStore = useWindowStore()

            // 响应式数据
            const activeTab = ref('0') // 0表示"全部"
            const currentPage = ref(1)
            const pageSize = ref(8)
            const downloading = reactive({})
            const searchKeyword = ref('')

            // 默认图标
            const defaultIcon = ''

            // 获取所有软件类型
            const categories = computed(() => {
                const types = windowStore.softList.map(item => item.type)
                // 添加"全部"选项作为默认选项
                return [{ id: 0, name: '全部', icon: 'CollectionTag' }, ...windowStore.softTypeList]
            })

            // 过滤后的软件列表（包含分类和搜索）
            const filteredSoftList = computed(() => {
                let result = windowStore.softList

                // 根据分类筛选
                if (activeTab.value !== '0') { // 0表示"全部"
                    const categoryId = parseInt(activeTab.value);
                    result = result.filter(item => item.types.includes(categoryId))
                }

                // 根据搜索关键词筛选
                if (searchKeyword.value) {
                    const keyword = searchKeyword.value.toLowerCase()
                    result = result.filter(item =>
                        item.name.toLowerCase().includes(keyword)
                    );
                }

                return result
            })

            // 分页后的软件列表
            const paginatedSoftList = computed(() => {
                const start = (currentPage.value - 1) * pageSize.value
                const end = start + pageSize.value
                return filteredSoftList.value.slice(start, end)
            })

            // 处理分类选择
            const handleCategorySelect = (category) => {
                activeTab.value = category
                currentPage.value = 1 // 切换分类时重置到第一页
                console.log('handleCategorySelect', category === activeTab)
            }

            // 获取分类软件数量
            const getCategoryCount = (categoryId) => {
                if (categoryId === 0) { // 0表示"全部"
                    return windowStore.softList.length
                }
                return windowStore.softList.filter(item => item.types.includes(categoryId)).length
            }

            // 处理搜索
            const handleSearch = () => {
                currentPage.value = 1 // 搜索时重置到第一页
            }

            // 处理分页大小变化
            const handleSizeChange = (val) => {
                pageSize.value = val
                currentPage.value = 1
            }

            // 处理当前页变化
            const handleCurrentChange = (val) => {
                currentPage.value = val
            }

            // 下载状态文本
            const getDownloadStatusText = (state) => {
                const statusMap = {
                    0: '未下载',
                    1: '下载中',
                    2: '已下载'
                }
                return statusMap[state] || '未知'
            }

            // 下载状态类型
            const getDownloadStatusType = (state) => {
                const typeMap = {
                    0: 'info',
                    1: 'warning',
                    2: 'success'
                }
                return typeMap[state] || 'info'
            }

            // 安装状态文本
            const getInstallStatusText = (state) => {
                const statusMap = {
                    0: '未安装',
                    1: '已安装'
                }
                return statusMap[state] || '未知'
            }

            // 安装状态类型
            const getInstallStatusType = (state) => {
                const typeMap = {
                    0: 'info',
                    1: 'success'
                }
                return typeMap[state] || 'info'
            }

            // 处理下载
            const handleDownload = async (software) => {
                ElMessage.info(`开始下载 ${software.name}`)
                // 使用更通用的默认下载路径
                const path = software.url;
                const id = software.id;
                // 设置下载状态为下载中
                downloading[software.id] = true
                const result = await ipcRenderer.invoke('download:start', { id, url: path, softName: software.name });
                if (result.success) {
                    // 设置下载状态为下载中
                    const index = windowStore.softList.findIndex(item => item.id === software.id)
                    if (index !== -1) {
                        windowStore.softList[index].downState = 1 // 标记为下载中
                    }
                } else {
                    downloading[software.id] = false
                    ElMessage.error('下载启动失败: ' + result.error);
                }

                // 模拟下载过程
                // setTimeout(() => {
                //     // 更新软件状态
                //     const index = windowStore.softList.findIndex(item => item.id === software.id)
                //     if (index !== -1) {
                //         if (windowStore.softList[index].downState === 2) {
                //             downloading[software.id] = false
                //             ElMessage.success(`${software.name} 下载完成`)
                //         }
                //         //windowStore.softList[index].downState = 2 // 标记为已下载
                //     }
                // }, 2000)
            }

            const getFileNameFromUrl = (url) => {
                const match = url.match(/[?&]fileName=([^&]*)/);
                if (match && match[1]) {
                    return decodeURIComponent(match[1]); // 注意解码，如空格被编码为 %20
                }
                return null;
            }
            // 处理安装
            const handleInstall = async (software) => {
                ElMessage.info(`开始安装 ${software.name}`);

                try {
                    // 获取下载目录
                    const savePath = await ipcRenderer.invoke('get-save-path');

                    // 从URL中提取文件名
                    const fileName = getFileNameFromUrl(software.url);
                    if (!fileName) {
                        ElMessage.error(`${software.name} 下载链接中未包含文件名`);
                        return;
                    }

                    // 构建下载文件路径
                    const downloadPath = `${savePath}/${fileName}`;

                    // 检查文件是否存在
                    const fs = require('fs');
                    if (!fs.existsSync(downloadPath)) {
                        ElMessage.error(`${software.name} 安装文件不存在，请先下载`);
                        return;
                    }

                    // 检查文件大小
                    const stats = fs.statSync(downloadPath);
                    if (stats.size === 0) {
                        ElMessage.error(`${software.name} 安装文件为空，请重新下载`);
                        return;
                    }

                    // 调用主进程安装软件
                    await ipcRenderer.invoke('install-software', { id: software.id, path: downloadPath });
                } catch (error) {
                    ElMessage.error(`${software.name} 安装失败: ${error.message}`);
                }
            }

            const handleDownloadPage = () => {
                ipcRenderer.invoke('show-download-panel');
            }

            // 添加响应式引用
            const downloadListener = ref(null)
            const installListener = ref(null)

            // 监听下载完成事件
            onMounted(() => {
                downloadListener.value = (event, data) => {
                    console.log('下载完成:', data);
                    const { id, status } = data;
                    // 更新软件状态
                    const index = windowStore.softList.findIndex(item => item.id === id)
                    if (index !== -1) {
                        if (status === 'completed') {
                            windowStore.softList[index].downState = 2 // 标记为已下载
                            downloading[id] = false
                            ElMessage.success(`${windowStore.softList[index].name} 下载完成`)
                        } else if (status === 'failed') {
                            downloading[id] = false
                            ElMessage.error(`${windowStore.softList[index].name} 下载失败`)
                        } else if (status === 'progress') {
                            // 可以在这里处理下载进度
                            windowStore.softList[index].downState = 1 // 标记为下载中
                        }
                    }
                }
                ipcRenderer.on('download:status', downloadListener.value)

                // 监听安装状态更新事件
                installListener.value = (event, data) => {
                    console.log('安装状态更新:', data);
                    const { id, status, error, message } = data; // 确保解构所有字段
                    // 查找对应的软件项
                    const index = windowStore.softList.findIndex(item => item.id === id)
                    if (index !== -1) {
                        if (status === 'completed') {
                            // 标记为已安装
                            windowStore.softList[index].installState = 1
                            // 修复：确保message变量正确使用
                            const msg = message ? `${windowStore.softList[index].name} ${message}` : `${windowStore.softList[index].name} 安装完成`
                            ElMessage.success(msg)
                        } else if (status === 'started') {
                            // 安装已启动，设置状态为安装中
                            windowStore.softList[index].installState = 2
                            ElMessage.info(`${windowStore.softList[index].name} 安装已启动`)
                        } else if (status === 'opened') {
                            // 文件已打开
                            ElMessage.info(`${windowStore.softList[index].name} 文件已打开，请按提示操作`)
                        } else if (status === 'failed') {
                            // 安装失败，重置状态
                            windowStore.softList[index].installState = 0
                            if (error && error.includes('取消')) {
                                ElMessage.warning(`${windowStore.softList[index].name} 安装被取消: ${error}`);
                            } else {
                                ElMessage.error(`${windowStore.softList[index].name} 安装失败: ${error || '未知错误'}`);
                            }
                        }
                    }
                }
                ipcRenderer.on('install-status', installListener.value)
            })

            // 移除监听器
            onUnmounted(() => {
                if (downloadListener.value) {
                    ipcRenderer.removeListener('download:status', downloadListener.value)
                }
                if (installListener.value) {
                    ipcRenderer.removeListener('install-status', installListener.value)
                }
            })

            return {
                windowStore,
                activeTab,
                currentPage,
                pageSize,
                downloading,
                searchKeyword,
                defaultIcon,
                categories,
                filteredSoftList,
                paginatedSoftList,
                Search,
                Download,
                handleDownloadPage,
                handleCategorySelect,
                getCategoryCount,
                handleSearch,
                handleSizeChange,
                handleCurrentChange,
                getDownloadStatusText,
                getDownloadStatusType,
                getInstallStatusText,
                getInstallStatusType,
                handleDownload,
                handleInstall,
                getFileNameFromUrl
            }
        }
    }
</script>

<style scoped>
    .el-row {
        margin-top: 5px;
    }

    .card-header h5 {
        margin: 0;
    }

    .card-refresh-btn {
        float: right;
        margin-top: -25px;
        cursor: pointer;
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }

    .card-header h3 {
        margin: 0;
        font-size: 18px;
    }

    .left-panel {
        height: 100%;
        width: 240px;
        /* 固定宽度 */
        flex-shrink: 0;
        /* 防止收缩 */
        padding-right: 10px;
        /* 保持间距 */
    }

    .right-panel {
        flex: 1;
        /* 占据剩余空间 */
        min-width: 0;
        /* 允许收缩 */
    }

    /* 修改外层容器为flex布局 */
    :deep(.el-row) {
        display: flex;
        flex-wrap: nowrap;
    }

    /* 自定义滚动条样式 */
    ::-webkit-scrollbar {
        width: 6px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }
</style>
<style scoped>
    .search-card,
    .category-card {
        display: flex;
        flex-direction: column;
        height: 100% !important;
        margin-bottom: 0px;
    }

    .card-header {
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }

    .card-header h3 {
        margin: 0;
        font-size: 18px;
    }

    .category-list {
        flex: 1;
        overflow-y: auto;
        min-height: 0;
        /* 允许在flex容器中收缩 */
    }

    .el-menu {
        border-right: none
    }

    .category-badge {
        margin-left: 15px;
        margin-top: -36px;
    }
</style>
<style scoped>
    /* 替换之前的.category-name样式 */
    .category-name {
        display: inline-grid;
        grid-template-columns: 1fr;
        width: 60px;
        /* 固定宽度 */
        text-align: center;
        font-size: 14px;
        margin: 0 8px;
        align-items: center;
        /* 强制不换行 */
        white-space: nowrap;
        /* 溢出隐藏 */
        overflow: hidden;
        /* 文本省略号 */
        text-overflow: ellipsis;
        color: var(--el-color-info);
    }

    /* 如果需要更好的中文对齐效果 */
    .el-menu-item span {
        display: flex;
        align-items: center;
    }
</style>
<style scoped>
    .software-list-container {
        overflow-y: auto;
        overflow-x: hidden;
    }

    .software-card {
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .software-icon {
        text-align: center;
        margin-bottom: 15px;
    }

    .software-icon .image {
        width: 80px;
        height: 80px;
        border-radius: 50%;
    }

    .software-info {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .software-name {
        margin: 0 0 10px 0;
        font-size: 16px;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .software-version,
    .software-size {
        margin: 5px 0;
        font-size: 14px;
        color: #666;
    }

    .software-status {
        margin: 10px 0;
    }

    .software-actions {
        margin-top: auto;
        display: flex;
        justify-content: space-between;
    }

    .pagination-container {
        display: flex;
        justify-content: center;
    }

    :deep(.el-pagination.is-background .el-pager li:not(.disabled).is-active) {
        background-color: #409eff;
    }

    :deep(.el-pagination.is-background .el-pager li:hover) {
        color: #409eff;
    }

    :deep(.el-pagination button:hover) {
        color: #409eff;
    }

    .header-actions {
        display: flex;
        align-items: center;
    }
</style>